#!/bin/bash

echo "##################################################"
echo "    split cue image into single flac songs."
echo "    scripts by hitmoon, <zxq_yx_007@163.com>"
echo "##################################################"

if [ $# -lt 1 ];then
	echo "$0 <cue file name>"
	exit 1;
fi

HERE=$(pwd)
if [[ $1 =~ ^/ ]]; then
    DIR=${1%/*}
else
    DIR1="$HERE/$1"
    DIR=${DIR1%/*}
fi
echo $DIR

CUE=$(basename "$1")

test_bin()
{
    for p in "$@"
    do
	type "$p" &>/dev/null
	if [ $? -ne 0 ]; then
	    echo "You must install package \"$p\" first!!"
	    exit 1
	fi
    done
}

conv_utf(){
echo "Converting cue file to UTF-8 format..."
enconv -x utf-8 "${CUE}"
}

split(){
FILE=$(cat "${CUE}" | awk -F \" '/FILE/ {print $2}')
FMT=${FILE##*.}
echo "Spliting file ${FILE}..."
shnsplit -i ${FMT} -f "${CUE}" -o flac "${FILE}"
}

rename(){
cat "${CUE}" | sed 's/\r//g' | sed -n '/ *TRACK /{N;s/\"//g;p;}' | grep 'TRACK' > part1
cat "${CUE}" | sed 's/\r//g' | sed -n '/ *TRACK /{N;s/\"//g;p;}' | grep 'TITLE' > part2
paste part1 part2 > tmp

echo "Rename file according cue file..."
cat tmp | while read -e line;
do 
	num=$(echo $line | cut -d' ' -f2)
	title=$(echo $line | cut -d' ' -f5-)
	mv -v split-track${num}.flac "${title}".flac
done
}

clean(){
rm -f part1 part2 tmp
echo "##################################################"
echo "Done, shnsplit flac file name renamed, Have fun!"
echo "##################################################"
}

test_bin shntool enconv
[ "X$HERE" != "X$DIR" ] && cd "${DIR}"
conv_utf
split
rename
clean
[ "X$HERE" != "X$DIR" ] && cd "${HERE}"

